const createError = require('http-errors')

function success(res, message, data = {}, code = 200) {
  res.status(code).json({
    status: true,
    message,
    data
  })
}

function failure(res, error) {
  let statusCode = 500
  let errors = '服务器错误'
  if (error.name === 'SequelizeValidationError') {
    errors = error.errors.map(e => e.message)
    return res.status(400).json({
      status: false,
      message: '请求参数错误',
      errors
    })
  }
  else if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
    statusCode = 401
    errors = "您提交的token错误或已经过期了"
  }
  else if (error instanceof createError.HttpError) {
    statusCode = error.statusCode
    errors = error.message
  }
  res.status(statusCode).json({
    status: false,
    message: `请求失败：${errors.name}`,
    errors: Array.isArray(errors) ? errors : [errors]
  })
}

  


module.exports = {
  success,
  failure
}